﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace HongYeSystemWebApi.Templet.Service
{
    public  class CommandService
    {

        public void Exceptcsv(List<List<string>> values,string Path)
        {
            ExportToCsv(values, Path);
        }
        public void ExportToCsv(List<List<string>> data, string filePath)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(filePath,false,Encoding.UTF8))
                {
                    foreach (var row in data)
                    {
                        writer.WriteLine(string.Join(",", row));
                    }
                }
                Console.WriteLine("CSV file exported successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error exporting CSV file: " + ex.Message);
            }
        }

        public   string GetColumnLetter(int columnNumber)
        {
            if (columnNumber <= 0) return "A"; // Excel列从1开始，如果为0则默认为A列

            string columnName = string.Empty;
            int num = columnNumber;
            while (num > 0)
            {
                int remainder = (num - 1) % 26;
                columnName = ((char)('A' + remainder)).ToString() + columnName;
                num = (num - 1) / 26;
            }

            return columnName;
        }


        public void DeleteFile(string Path)
        {

            //Directory.GetFiles(Path);
            if (Directory.Exists(Path))
            {
                try
                {
                    // 获取目录下的所有文件
                    DirectoryInfo directory = new DirectoryInfo(Path);
                    FileInfo[] files = directory.GetFiles();

                    // 根据文件的创建时间排序
                    var sortedFiles = files.OrderByDescending(f => f.CreationTime).ToArray();
                    // 删除超过20个的文件
                    for (int i = 20; i < sortedFiles.Length; i++)
                    {
                        sortedFiles[i].Delete();
                    }

                    Console.WriteLine("前20个文件已保留，其余文件已删除。");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"发生错误: {ex.Message}");
                }
            }
            //else
            //{
            //    Console.WriteLine("目标目录不存在。");
            //}
        }
    }
}
